package com.heima.search.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.thread.ApTheadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.BooleanQuery;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author shitou
 * @className ArticleSearchServiceImpl
 * @description: TODO
 */
@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Resource
    private RestHighLevelClient restHighLevelClient;


    @Resource
    private ApUserSearchService approveService;

    /**
     * es文章分页检索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        if (!StringUtils.isNotBlank(dto.getSearchWords())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 调用搜索记录
        ApUser apUser = ApTheadLocalUtil.getApUser();
        if (apUser != null) {
            approveService.insert(dto.getSearchWords(), apUser.getId());
        }

        // 创建搜索请求对象，并且指定索引库
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        // 复合查询 关键字查询
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.must(QueryBuilders.matchQuery("all", dto.getSearchWords()));
        //小于最小时间
        if (dto.getMinBehotTime() != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lte(dto.getMinBehotTime()));
        }
        searchRequest.source().query(boolQueryBuilder);
        //分页
        searchRequest.source().from(0).size(dto.getPageSize());
        //排序
        searchRequest.source().sort("publishTime", SortOrder.DESC);
        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false);
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        searchRequest.source().highlighter(highlightBuilder);
        // 结果封装
        // 索引请求
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        return result(searchResponse);
    }


    /**
     * 抽取的封装结果的方法
     *
     * @param searchResponse
     * @return ResponseResult
     */

    private ResponseResult result(SearchResponse searchResponse) {
        List<Map> list = new ArrayList<>();
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            //获取查询结果，返回是map集合
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            //高亮数据封装
            //如果高亮域中有值
            if (hit.getHighlightFields().size() > 0) {
                //取出高亮域
                Text[] titles = hit.getHighlightFields().get("title").fragments();
                if (titles.length > 0) {
                    //把高亮之后的h_tile=<font>测试</font>
                    sourceAsMap.put("h_title", titles[0].toString());
                }
            } else {
                //表示没有高亮域，我们则把h_title=测试
                sourceAsMap.put("h_title", sourceAsMap.get("title"));
            }
            list.add(sourceAsMap);
        }
        return ResponseResult.okResult(list);
    }
}
